import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from "@nestjs/common";
import { Request, Response } from "express";

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const req = ctx.getRequest<Request>();
    const res = ctx.getResponse<Response>();
    // const request = ctx.getRequest()
    console.error(
      `request：${req.path}[${res.statusCode}]: ${exception.message}`
    );

    //拦截异常
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    if (exception.status === HttpStatus.NOT_FOUND) {
      res.status(exception.getStatus()).json({ message: "koa.NotFound" });
      return;
    }
    res.status(exception.getStatus()).json({ message: exception.message });
  }
}
